package com.kaili.basic.controller;

import com.baomidou.mybatisplus.plugins.Page;
import com.kaili.basic.pojo.dto.*;
import com.kaili.basic.pojo.entity.MdmRoleExport;
import com.kaili.basic.pojo.entity.MdmRoleQueryEntity;
import com.kaili.basic.pojo.vo.MdmRoleVO;
import com.kaili.basic.service.BaseMenuRoleService;
import com.kaili.basic.service.BaseMenuService;
import com.kaili.basic.service.IBaseRolePowerService;
import com.kaili.basic.version.ApiVersion;
import com.kaili.common.aop.OperateLogAspect;
import com.kaili.common.aop.log.enums.FunctionName;
import com.kaili.common.aop.log.enums.OperateType;
import com.kaili.common.exception.RestException;
import com.kaili.common.pojo.entity.BaseMenu;
import com.kaili.common.response.CommonStatus;
import com.kaili.common.response.RestStatus;
import com.kaili.common.util.ExcelUtil;
import com.kaili.common.util.LoginDetailUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * 角色权限管理控制类
 * Created by linjian on 19-8-5.
 */
@ApiVersion(1)
@RequestMapping("/{api_version}")
@Api(tags = "角色权限管理", description = "角色权限管理相关API")
@RestController
public class MdmRoleManagerController {

    @Autowired
    private IBaseRolePowerService iBaseRolePowerService;
    @Autowired
    BaseMenuService baseMenuService;
    @Autowired
    BaseMenuRoleService baseMenuBaseRoleService;

    /**
     * 按条件查询
     */
    @GetMapping("/rolePowerManager/query")
    @ApiOperation(value = "按条件查询权限", notes = "按条件查询权限")
    public Page<MdmRoleVO> queryRoleByConditions(@ModelAttribute MdmRoleQueryDto dto){
        return iBaseRolePowerService.queryRoleByConditions(new Page<MdmRoleVO>(dto.getPage(), dto.getPageSize()), dto);
    }

    /**
     * 新增
     */
    @ApiOperation(value = "新增权限", notes = "新增权限")
    @OperateLogAspect(functionName = FunctionName.mdmRoleManager,operateType = OperateType.ADD, key = "base.user.role")
    @PostMapping("/rolePowerManager/addRole")
    public RestStatus addRoleManager(@RequestBody MdmRoleAddDto dto){
        MdmRoleVO mdmRoleVO = new MdmRoleVO();
        BeanUtils.copyProperties(dto, mdmRoleVO);
        Long createBy = LoginDetailUtils.getCurrentEmployeeId().longValue();
        if (createBy == null){
            mdmRoleVO.setCreatedBy(-1L);
        }
        mdmRoleVO.setCreatedBy(createBy);
        mdmRoleVO.setCreatedTime(new Date());
        int id = getRoleId(mdmRoleVO.getRoleCode());
        //将编号状态改为正在使用
        iBaseRolePowerService.updateRoleCodeUsing(id);
        int result = iBaseRolePowerService.addRoleManager(mdmRoleVO);
        if (result == 1){
            iBaseRolePowerService.updateRoleCodeUsed(id);
        }else{
            iBaseRolePowerService.updateRoleCodeUnuse(id);
            return CommonStatus.ADD_FAIL;
        }
        return CommonStatus.ADD_OK;
    }

    /**
     * 点击编辑,查询角色权限信息
     * @param id
     * @return
     */
    @ApiOperation(value = "编辑权限", notes = "编辑权限")
    @GetMapping("/rolePowerManager/editRole/{id}")
    public MdmRoleQueryEntity editRole(@ApiParam("id") @PathVariable("id") Integer id){
        return iBaseRolePowerService.queryRoleInfoById(id);
    }

    @ApiOperation(value = "更新角色名称", notes = "更新角色名称")
    @OperateLogAspect(functionName = FunctionName.mdmRoleManager,operateType = OperateType.UPDATE, key = "base.user.role")
    @PutMapping("/rolePowerManager/updateRoleName")
    public RestStatus updateRoleName(@RequestBody MdmRoleAddDto dto){
        iBaseRolePowerService.updateRoleName(dto);
        return CommonStatus.UPDATE_OK;
    }


    /***
     * 删除权限
     */
    @ApiOperation(value = "删除权限" ,notes = "删除权限")
    @OperateLogAspect(functionName = FunctionName.mdmRoleManager,operateType = OperateType.DELETE, key = "base.user.role")
    @DeleteMapping("/rolePowerManager/deleteRole/{id}")
    public RestStatus deleteRole(@ApiParam("id") @PathVariable("id") Integer id){
        iBaseRolePowerService.deleteRoleById(id);
        return CommonStatus.DELETE_OK;
    }

    /***
     * 更新角色权限
     */
    @ApiOperation(value = "更新角色权限", notes = "更新角色权限")
    @OperateLogAspect(functionName = FunctionName.mdmRoleManager,operateType = OperateType.UPDATE, key = "base.user.role")
    @PutMapping("/rolePowerManager/update")
    public RestStatus updateUserRole(@RequestBody MdmRoleAddMenuDto dto){
        MdmRoleVO mdmRoleVO = new MdmRoleVO();
        BeanUtils.copyProperties(dto, mdmRoleVO);
        Long modifyBy = LoginDetailUtils.getCurrentEmployeeId().longValue();
        if (modifyBy == null){
            mdmRoleVO.setModifyBy(-1L);
        }
        mdmRoleVO.setModifyBy(modifyBy);
        mdmRoleVO.setModifyTime(new Date());
        iBaseRolePowerService.updateRoleById(mdmRoleVO);
        return CommonStatus.UPDATE_OK;
    }


    /**
     * 自动生成角色编号
     */
    @ApiOperation(value = "自动生成角色编号", notes = "自动生成角色编号")
    @PostMapping("/rolePowerManager/roleCode")
    public String getRoleCodeByAuto(){
        //首先查询是否存在可以使用的编码，若不存在，就自动生成返回给前端
        Integer code =  iBaseRolePowerService.getUsableCode();
        if (null == code){
            Map<String,Object> timeMap = new HashMap<>();
            Date createdTime = new Date();
            Date optTime = null;
            timeMap.put("createdTime",createdTime);
            timeMap.put("optTime",optTime);
            iBaseRolePowerService.createdVersionCode(timeMap);
            code = iBaseRolePowerService.getUsableCode();
        }
        String roleCode = code.toString();
        String zero = "0";
        if (roleCode.length()<6){
            int index = 6 - roleCode.length();
            for (int i = 0;i<index;i++){
                roleCode = zero+roleCode;
            }
        }
        return roleCode;
    }

    public Integer getRoleId(String roleCode){
        return Integer.parseInt(roleCode);
    }


    /**
     * 导出角色信息
     */
    @GetMapping("/rolePowerManager/export")
    @ApiOperation(value = "导出角色权限信息")
    public void export(HttpServletResponse response, @ModelAttribute MdmRoleQueryDto dto) throws RestException {
        List<MdmRoleExport> list = iBaseRolePowerService.rolesInfoExport(dto);
        ExcelUtil.exportExcel(list,"角色权限信息","sheet1", MdmRoleExport.class, UUID.randomUUID().toString()+".xls",response);
    }

    /**
     * 分配角色权限
     */
    @PostMapping(value = "rolePowerManager/assignment")
    @OperateLogAspect(functionName = FunctionName.mdmRoleManager,operateType = OperateType.ADD, key = "base.user.role")
    @ApiOperation(value = "角色分配权限", notes = "角色分配权限")
    public RestStatus updateBaseMenuRole(@RequestBody MdmRoleAddMenuDto dto) {
        MdmRoleVO baseRole = new MdmRoleVO();
        baseRole.setId(dto.getId());
        baseRole.setMids(dto.getMids());
        baseMenuBaseRoleService.updateBaseMenuRole(baseRole.getId().longValue(), baseRole.getMids());
        return CommonStatus.ADD_OK;
    }

    /**
     * 查询菜单列表数组
     */
    @GetMapping(value = "/rolePowerManager/menu/{rid}")
    @ApiOperation(value = "获取菜单", notes = "根据角色Id获取角色对应菜单")
    public Map<String, Object> baseMenuTree(@PathVariable Integer rid) {
        Map<String, Object> map = new LinkedHashMap<>();
        List<BaseMenu> baseMenus = baseMenuService.baseMenuTree();
        map.put("baseMenus", baseMenus);
        List<Long> selMids = baseMenuService.getBaseMenusByRid(rid);
        map.put("mids", selMids);
        return map;
    }
}
